import datetime
import time

from flask import request, render_template, g, redirect, url_for, logging, session, current_app, abort, jsonify

from info import constants, response_code, db
from info.models import User, News, Category
from info.modules.admin import admin_blue
from info.utils.comment import user_login_data
from info.utils.file_storage import upload_file


@admin_blue.route('/news_type', methods=['GET', 'POST'])
def news_type():
    """新闻分类
    1.展示新闻分类
    2.增加或者修改新闻分类
    """
    # 1.展示新闻分类
    if request.method == 'GET':
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            logging.error(e)
            abort(404)
        # 取出最新
        categories.pop(0)

        context = {
            'categories':categories
        }

        return render_template('admin/news_type.html',context=context)

    # 2.增加或者修改新闻分类
    if request.method == 'POST':
        # 2.1 接受参数：cid, cname
        cid = request.json.get('id')
        cname = request.json.get('name')

        # 2.2 校验参数：cid是可选的参数，cname必传
        if not cname:
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='缺少参数')

        # 2.3 根据cid判断，是新增分类还是修改分类（核心代码）
        if cid:
            # 修改分类
            try:
                category = Category.query.get(cid)
            except Exception as e:
                logging.error(e)
                return jsonify(errno=response_code.RET.DBERR, errmsg='查询新闻分类失败')
            if not category:
                return jsonify(errno=response_code.RET.NODATA, errmsg='分类不存在')

            # 将传入的cname，重新的赋值给category的name属性
            category.name = cname
        else:
            # 新增分类
            category = Category()
            category.name = cname
            db.session.add(category)

        # 2.4 同步到数据
        try:
            db.session.commit()
        except Exception as e:
            logging.error(e)
            db.session.rollback()
            return jsonify(errno=response_code.RET.DATAERR, errmsg='更新数据失败')

        # 2.5 响应结果
        return jsonify(errno=response_code.RET.OK, errmsg='更新数据成功')


@admin_blue.route('/news_edit_detail/<int:news_id>', methods=['GET','POST'])
def news_edit_detail(news_id):
    """新闻板式编辑详情
    1.查询新闻详情数据
    2.查询新闻分类数据（"最新"分类除外）
    3.构造渲染数据
    4.渲染界面
    """
    # 1.展示新闻板式编辑详情
    if request.method == 'GET':
        # 1.查询新闻详情数据
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            logging.error(e)
            abort(404)

        if not news:
            abort(404)

        # 2.查询新闻分类数据（"最新"分类除外）
        categories = []
        try:
            categories = Category.query.all()
            categories.pop(0)
        except Exception as e:
            logging.error(e)

        # 3.构造渲染数据
        context = {
            'news': news.to_dict(),
            'categories': categories
        }

        # 4.渲染界面
        return render_template('admin/news_edit_detail.html', context=context)

    # 2.实现新闻板式编辑后端
    if request.method == 'POST':
        # 2.1 接受参数
        title = request.form.get("title")
        digest = request.form.get("digest")
        content = request.form.get("content")
        index_image = request.files.get("index_image")
        category_id = request.form.get("category_id")

        # 2.2 校验参数
        if not all([title, digest, content, category_id]):
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='缺少参数')

        try:
            news = News.query.get(news_id)
        except Exception as e:
            logging.error(e)
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='查询新闻数据失败')

        if not news:
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='新闻不存在')

        # 2.3 如果运营修改了图片，我们就需要将图片上传到七牛云；反之，就不管
        if index_image:
            try:
                index_image_data = index_image.read()
            except Exception as e:
                logging.error(e)
                return jsonify(errno=response_code.RET.PARAMERR, errmsg='图片参数错误')

            try:
                key = upload_file(index_image_data)
            except Exception as e:
                logging.error(e)
                return jsonify(errno=response_code.RET.THIRDERR, errmsg='上传图片到七牛云失败')

            # 需要将key修改
            news.index_image_url = constants.QINIU_DOMIN_PREFIX + key

        # 2.4 将新闻编辑的数据保存到模型对象，并同步到数据库
        news.title = title
        news.digest = digest
        news.content = content
        news.category_id = category_id

        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            logging.error(e)
            return jsonify(errno=response_code.RET.DBERR, errmsg='保存数据失败')

        # 2.5 响应结果
        return jsonify(errno=response_code.RET.OK, errmsg='OK')


@admin_blue.route('/news_edit')
def news_edit():
    """展示新闻板式编辑列表"""

    # 接受参数
    page = request.args.get('p', 1)
    keyword = request.args.get('keyword', None)

    # 校验参数
    try:
        page = int(page)
    except Exception as e:
        logging.error(e)
        page = 1

    # 分页查询：查询待审核的 (核心代码)
    news_list = []
    total_page = 1
    current_page = 1
    try:
        if keyword:
            paginate = News.query.filter(News.status == 0, News.title.contains(keyword)).order_by(
                News.create_time.desc()).paginate(page,
                                                  constants.ADMIN_NEWS_PAGE_MAX_COUNT,
                                                  False)
        else:
            paginate = News.query.filter(News.status == 0).order_by(
                News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news_list = paginate.items
        total_page = paginate.pages
        current_page = paginate.page

    except Exception as e:
        logging.error(e)
        abort(404)

    # 构造渲染数据
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())

    context = {
        'news_list': news_dict_list,
        'total_page': total_page,
        'current_page': current_page
    }

    # 响应结果
    return render_template('admin/news_edit.html', context=context)


@admin_blue.route('/news_review_action', methods=['POST'])
def news_review_action():
    """新闻审核实现"""
    # 1.接受参数
    news_id = request.json.get('news_id')
    action = request.json.get('action')

    # 2.校验参数
    if not all([news_id, action]):
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='缺少参数')
    if action not in ['accept', 'reject']:
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='参数错误')

    # 3.查询要审核的新闻
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.DBERR, errmsg='查询新闻数据失败')
    if not news:
        return jsonify(errno=response_code.RET.NODATA, errmsg='新闻不不存在')

    # 4.修改要审核的新闻的状态
    if action == 'accept':
        news.status = 0
    else:
        # 拒绝通过审核
        news.status = -1
        # 拒绝原因
        reason = request.json.get('reason')
        if not reason:
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='请输⼊入拒绝原因')

        news.reason = reason
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.DATAERR, errmsg='保存审核信息失败')

    # 5.响应审核结果
    return jsonify(errno=response_code.RET.OK, errmsg='OK')


@admin_blue.route('/news_review_detail/<int:news_id>')
def news_review_detail(news_id):
    """待审核新闻详情"""
    # 响应待审核新闻详情界⾯面# 查询新闻详情信息
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        logging.error(e)
        abort(404)
    if not news:
        abort(404)
    context = {
        'news': news.to_dict()
    }
    # 响应待审核新闻详情界⾯面
    return render_template('admin/news_review_detail.html', context=context)


@admin_blue.route('/news_review')
def news_review():
    """新闻审核"""
    # 以下代码是:查询待审核新闻数据
    # 1.接受参数
    page = request.args.get('p', 1)
    keyword = request.args.get('keyword')

    # 2.校验参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 3.分页查询
    news_list = []
    total_page = 1
    current_page = 1
    try:
        if keyword:
            paginate = News.query.filter(News.status != 0, News.title.contains(keyword)).order_by(News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        else:
            paginate = News.query.filter(News.status != 0).order_by(News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)

        news_list = paginate.items
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)

    # 4.构造渲染数据
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_review_dict())

    context = {
        'news_list': news_dict_list,
        'total_page': total_page,
        'current_page': current_page
        }

    # 5.响应结果
    return render_template('admin/news_review.html', context=context)


@admin_blue.route('/user_list')
def user_list():
    """用户列表
    1。接收参数
    2。校验参数
    3。分页查询
    4。响应结果
    """
    # 1。接收参数
    page = request.args.get('p', 1)
    # 2。校验参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 3.分页查询
    users = []
    total_page = 1
    current_page = 1
    try:
        paginate = User.query.filter(User.is_admin == False).paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        users = paginate.items
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)

    # 4.构造渲染数据
    user_dict_list = []
    for user in users:
        user_dict_list.append(user.to_admin_dict())

    context = {
        'users': user_dict_list,
        'total_page': total_page,
        'current_page': current_page
    }

    # 5.响应结果
    return render_template('admin/user_list.html', context=context)


@admin_blue.route('/user_count')
def user_count():
    """用户统计
    1.查询用户总数量
    2.查询用户月新增数
    3.查询用户日新增数
    4.查询用户日活跃量
    5.渲染用户统计界面
    """

    total_count = 0
    month_count = 0
    day_count = 0
    # 1.查询用户总数量
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 2.查询用户月新增数
    t = time.localtime()
    month_begin = '%d-%02d-01' % (t.tm_year, t.tm_mon)
    month_begin_date = datetime.datetime.strptime(month_begin, '%Y-%m-%d')

    try:
        month_count = User.query.filter(User.is_admin == False, User.create_time > month_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 3.查询用户日新增数
    day_begin = '%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)
    day_begin_date = datetime.datetime.strptime(day_begin, '%Y-%m-%d')

    try:
        day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 4.查询用户日活跃量
    # 定义空数组，保存数据
    active_date = []
    active_count = []

    # 计算31天以内的每天间隔
    for i in range(31):
        # 计算一天开始
        begin_date = day_begin_date - datetime.timedelta(days=i)
        # 计算一天结束
        end_date = day_begin_date - datetime.timedelta(days=(i - 1))
        # 计算活跃量
        count = User.query.filter(User.is_admin== False, User.last_login>=begin_date, User.last_login<end_date).count()
        active_count.append(count)
        active_date.append(datetime.datetime.strftime(begin_date, '%Y-%m-%d'))

    # 反转⽇期和数量，保证时间线从左⾄至右递增
    active_count.reverse()
    active_date.reverse()

    context = {
        'total_count': total_count,
        'month_count': month_count,
        'day_count': day_count,
        'active_date': active_date,
        'active_count': active_count
    }

    # 5.渲染用户统计界面
    return render_template('admin/user_count.html', context=context)


@admin_blue.route('/')
@user_login_data
def admin_index():
    """后台管理主页"""
    # 读取登录用户信息
    user = g.user
    if not user:
        # 如果用户未登录进⼊登录⻚面
        return redirect(url_for('admin.admin_login'))

    # 渲染主⻚页⽤用户信息
    context = {
        'user': user
    }

    # 渲染主页
    return render_template('admin/index.html', context=context)


@admin_blue.route('/login', methods=['GET', 'POST'])
@user_login_data
def admin_login():
    """后台管理理员登录"""
    # 1.渲染登录界⾯
    if request.method == 'GET':
        # 如果管理理员已经登录，再次访问登录界⾯面时就直接进⼊主页
        user = g.user
        if user and user.is_admin:
            return redirect(url_for('admin.admin_index'))
        return render_template('admin/login.html')

    # 2.实现登录后端逻辑
    if request.method == 'POST':
        # 2.1获取参数
        username = request.form.get('username')
        password = request.form.get('password')

        # 2.2校验参数
        if not all([username, password]):
            return render_template('admin/login.html', errmsg='缺少参数')

        # 2.3查询登录用户和校验密码:登录用户必须是管理员的身份
        try:
            user = User.query.filter(User.nick_name == username, User.is_admin == 1).first()
        except Exception as e:
            logging.error(e)
            return render_template('admin/login.html', errmsg='查询用户失败')
        if not user:
            return render_template('admin/login.html', errmsg='用户名或密码错误')

        if not user.check_password(password):
            return render_template('admin/login.html', errmsg='用户名或密码错误')

        # 2.4状态保持
        session['user_id'] = user.id
        session['mobile'] = user.mobile
        session['nick_name'] = user.nick_name
        session['is_admin'] = user.is_admin  # 管理员用户登录时，需要添加身份信息作为状态保持信息，后续会用于检验该用户是否是管理员

        # 2.5响应登录结果
        return redirect(url_for('admin.admin_index'))
